<template>
  <div class="any-table">
    <!-- 搜索区域 -->
    <div class="any-table-search" v-if="$slots.tableSearch">
      <slot name="tableSearch"></slot>
    </div>

    <!-- 统一工具栏（合并原来的toolbar和actions） -->
    <div class="any-table-toolbar">
      <div class="any-table-toolbar-left">
        <slot name="tableToolbar"></slot>
      </div>
      <div class="any-table-toolbar-right">
        <!-- 额外操作按钮区域 -->
        <div class="any-table-extra-actions" v-if="$slots.tableActions">
          <slot name="tableActions"></slot>
        </div>

        <!-- 列显示控制 -->
        <a-dropdown trigger="click" placement="bottomRight">
          <a-tooltip title="列显示设置" placement="top">
            <a-button type="text" class="column-control-btn">
              <SettingOutlined class="column-control-icon" />
            </a-button>
          </a-tooltip>
          <template #overlay>
            <a-menu class="column-control-menu">
              <div class="column-menu-header">
                <span class="column-menu-title">列显示设置</span>
              </div>
              <a-menu-divider />
              <a-menu-item v-for="col in internalColumns" :key="col.key" class="column-menu-item">
                <a-checkbox
                  v-model:checked="col.visible"
                  :disabled="col.key === 'op' || col.key === 'action'"
                >
                  {{ col.title }}
                </a-checkbox>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>

    <!-- 表格主体 -->
    <a-table
      ref="tableRef"
      :columns="visibleColumns"
      :dataSource="tableData"
      :loading="tableLoading"
      :pagination="tablePagination"
      :rowKey="tableRowKey"
      :scroll="tableScroll"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <slot name="tableCell" :column="column" :record="record" :index="index"></slot>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { SettingOutlined } from '@ant-design/icons-vue'

interface AnyTableProps {
  tableColumns: any[]
  dataLoader?: Function
  searchParams?: any
  autoLoad?: boolean
  tableRowKey?: string
  tableScroll?: any
  pageSize?: number
}

const props = withDefaults(defineProps<AnyTableProps>(), {
  autoLoad: false,
  tableRowKey: 'id',
  tableScroll: undefined,
  pageSize: 10
})

const emit = defineEmits(['loadComplete'])

const tableLoading = ref(false)
const tableData = ref([])

// 内部列配置（添加 visible 属性）
const internalColumns = ref<any[]>([])

// 初始化列配置
const initColumns = () => {
  internalColumns.value = props.tableColumns.map(col => ({
    ...col,
    visible: col.visible !== undefined ? col.visible : true
  }))
}

// 可见的列
const visibleColumns = computed(() => {
  return internalColumns.value.filter(col => col.visible)
})

// 监听 tableColumns 变化
watch(() => props.tableColumns, () => {
  initColumns()
}, { immediate: true, deep: true })

const pagination = reactive({
  current: 1,
  pageSize: props.pageSize,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条数据`
})

// 在 computed 部分修改 tablePagination
const tablePagination = computed(() => ({
  current: pagination.current,
  pageSize: pagination.pageSize,
  total: pagination.total,
  showSizeChanger: true,
  showQuickJumper: true,  // 添加这行启用页码跳转
  showTotal: (total: number, range: [number, number]) => 
    `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`,
  onChange: (page: number, size: number) => {
    pagination.current = page
    pagination.pageSize = size
    loadTableData()  // 添加这行确保数据重新加载
  },
  onShowSizeChange: (current: number, size: number) => {
    pagination.current = 1  // 改变页面大小时重置到第一页
    pagination.pageSize = size
    loadTableData()  // 添加这行确保数据重新加载
  }
}))

// 加载表格数据
const loadTableData = async () => {
  if (!props.dataLoader) return

  tableLoading.value = true
  try {
    const requestParams = {
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
      ...props.searchParams
    }

    const response = await props.dataLoader(requestParams)
    tableData.value = response.records || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('AnyTable load data error:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    tableLoading.value = false
    emit('loadComplete')
  }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  console.log('AnyTable change:', pag, filters, sorter)
  
  // 处理分页变化
  if (pag) {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
    loadTableData()  // 确保这行存在
  }
  
  // 可以在这里处理排序和筛选逻辑
}

// 刷新表格数据
const refreshTable = (resetToFirstPage = false) => {
  if (resetToFirstPage) {
    pagination.current = 1
  }
  loadTableData()
}

// 重置表格到第一页
const resetTable = () => {
  pagination.current = 1
  loadTableData()
}

// 获取当前表格数据
const getTableData = () => {
  return tableData.value
}

// 获取选中的行数据（如果需要的话）
const getSelectedRows = () => {
  // 这里可以扩展选择功能
  return []
}

// 暴露方法给父组件
defineExpose({
  refreshTable,
  resetTable,
  loadTableData,
  getTableData,
  getSelectedRows
})

onMounted(() => {
  if (props.autoLoad) {
    nextTick(() => {
      loadTableData()
    })
  }
})
</script>

<style scoped>
.any-table {
  .any-table-toolbar {
    margin-bottom: 16px;
  }

  .any-table-search {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  .any-table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    min-height: 40px;
    padding: 0 4px;
  }

  .any-table-toolbar-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .any-table-toolbar-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .any-table-extra-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .column-control-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    color: #8c8c8c;
    background: #ffffff;
    border: 1px solid #e8e8e8;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
    transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    cursor: pointer;
  }

  .column-control-btn:hover {
    color: #1890ff;
    background: #f0f8ff;
    border-color: #91caff;
    box-shadow: 0 4px 8px rgba(24, 144, 255, 0.15);
    transform: translateY(-1px);
  }

  .column-control-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
  }

  .column-control-icon {
    font-size: 14px;
    transition: transform 0.2s ease;
  }

  .column-control-btn:hover .column-control-icon {
    transform: rotate(90deg);
  }

  .mg-b-30 {
    margin-bottom: 30px;
  }
}

.column-control-menu {
  min-width: 180px;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  border: 1px solid #f0f0f0;
}

.column-menu-header {
  padding: 12px 16px 8px;
}

.column-menu-title {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
}

.column-menu-item {
  padding: 0 !important;
}

.column-menu-item :deep(.ant-menu-title-content) {
  padding: 8px 16px;
  margin: 0;
}

.column-menu-item :deep(.ant-checkbox-wrapper) {
  width: 100%;
  padding: 0;
  font-size: 14px;
}

.column-menu-item:hover {
  background: #f5f5f5;
}

.column-menu-item :deep(.ant-checkbox-wrapper:hover) {
  background: transparent;
}
</style>